package im.demo.fileserv;

import im.demo.fileserv.db.tables.records.FilesRecord;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.nio.file.Paths;
import java.util.List;
import java.util.Optional;
import java.util.Properties;

@WebServlet(name = "FileListServlet", urlPatterns = {"/file_list"})
public class FileListServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Integer limit = Integer.parseInt(Optional.ofNullable(req.getParameter("limit")).orElse("100"));
        Integer offset = Integer.parseInt(Optional.ofNullable(req.getParameter("offset")).orElse("0"));

        List<FilesRecord> list = DB.getAllFile(offset, limit);

        System.out.println(list); // print table

        Properties fileProps = (Properties)req.getServletContext().getAttribute("fileProps");

        req.setAttribute("fileList", list);
        req.setAttribute("contextPath", req.getContextPath());

        String fileServeBaseUrl = new URL(fileProps.getProperty("fileserver.baseurl") + fileProps.getProperty("fileserver.contextpath")).toString();

        req.setAttribute("fileServeBaseUrl", fileServeBaseUrl);

        req.getRequestDispatcher("/files.ftl").forward(req, resp);

    }
}
